package cn.jetpiece.cloud.joss.app.modular.accessor.context;

import cn.hutool.core.util.StrUtil;
import cn.jetpiece.cloud.core.util.HttpContext;
import cn.jetpiece.cloud.joss.api.constant.AccessorCache;
import cn.jetpiece.cloud.joss.api.constant.BaseOssConstants;
import cn.jetpiece.cloud.joss.app.core.constant.OssConstants;
import cn.jetpiece.cloud.joss.app.modular.object.entity.Bucket;
import cn.jetpiece.cloud.joss.app.modular.object.enums.BasicExceptionEnum;
import cn.jetpiece.cloud.model.util.SpringContextHolder;
import lombok.extern.slf4j.Slf4j;
import cn.jetpiece.cloud.model.exception.ServiceException;
import org.springframework.data.redis.core.RedisTemplate;

import javax.servlet.http.HttpServletRequest;

/**
 * @author XuJZ
 * @since 2020/12/15
 */
@Slf4j
public class AccessorContext {

    private final RedisTemplate<String, Object> redisTemplate;

    public AccessorContext(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public static AccessorContext me() {
        return SpringContextHolder.getBean(AccessorContext.class);
    }


    /**
     * 获取当前accessor
     * <p>
     * 先从ThreadLocal中拿获取当前accessor，如果有值就直接返回，没取到再去redis取,完了把当前accessor放到Threadlocal里
     */
    public AccessorCache getAccessor() {
        AccessorCache current = AccessorContextHolder.get();
        if (current != null) {
            return current;
        } else {
            String accessKey = getCurrentAccessKey();
            if (accessKey == null || accessKey.length() <= 0) {
                throw new ServiceException(BasicExceptionEnum.ACCESSOR_NOT_EXISTED);
            }
            AccessorCache accessor = (AccessorCache) redisTemplate.boundHashOps(BaseOssConstants.ACCESSOR).get(accessKey);

            //临时缓存
            AccessorContextHolder.set(accessor);
            return accessor;
        }
    }

    /**
     * 获取当前AccessKey
     */
    public String getCurrentAccessKey() {
        HttpServletRequest request = HttpContext.getRequest();
        //如果请求是在http环境下，则有request对象
        if (request != null) {
            String accessKey = request.getHeader("accessKey");
            if (StrUtil.isNotEmpty(accessKey)) {
                return accessKey;
            }
            accessKey = request.getParameter("accessKey");
            if (StrUtil.isNotEmpty(accessKey)) {
                return accessKey;
            }
        }
        return null;
    }

    /**
     * 获取默认桶ID
     */
    public String getDefaultBucketName() {
        return getAccessor().getDefaultBucketName();
    }

    /**
     * 获取默认桶
     */
    public Bucket getDefaultBucket(String bucketId) {
        return (Bucket) redisTemplate.boundHashOps(OssConstants.BUCKET).get(bucketId);
    }

    /**
     * 获取默认桶
     */
    public Bucket getDefaultBucket() {
        return getDefaultBucket(getAccessor().getDefaultBucketName());
    }
}
